package com.hobart.learning.lagou.edu.IPersistence.config;


import com.hobart.learning.lagou.edu.IPersistence.io.Resource;
import com.hobart.learning.lagou.edu.IPersistence.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author ：hobart
 * @date ：Created in 2020-11-10 15:03
 * @description：
 * @modified By：
 * @version: $
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法是使用Dom4J对配置文件进行解析，封装成Configration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws PropertyVetoException, DocumentException {


        // dataSource 读取
        Document document = new SAXReader().read(inputStream);
        // <configuration>
        Element rootElement = document.getRootElement();

        // <property>
        List<Element> propertyNodes = rootElement.selectNodes("//property");

        Properties properties = new Properties();
        propertyNodes.forEach( element -> {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        });

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        System.out.println("driverClass = " + properties.getProperty("driverClass"));
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        System.out.println("jdbcUrl = " + properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        System.out.println("username = " + properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        System.out.println("password = " + properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        // mapper 读取
        List<Element> mapperNodes = rootElement.selectNodes("//mapper");


        for (Element element : mapperNodes) {
            String resourcePath = element.attributeValue("resource");
            InputStream resourceAsStream = Resource.getResourceAsStream(resourcePath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }


}
